<template>
  <div class="h-[calc(100vh-50px)]">
    <div class="app-content">
      <!--tab-->
      <el-tabs v-model="tabsName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="平台列表" name="0" />
        <el-tab-pane label="回收站" name="1" />
      </el-tabs>
      <!--平台头部-->
      <div class="flex justify-between">
        <el-form :inline="true" :model="searchData">
          <el-form-item class="w-240px" label="平台类型">
            <el-select v-model="searchData.type" placeholder="选择平台类型">
              <el-option :key="0" label="全部" value="" />
              <el-option v-for="item in platformTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="平台名称">
            <el-input v-model="searchData['name like']" placeholder="输入平台名称" />
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="searchData['username like']" placeholder="输入用户昵称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="warning" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="dialogChoosePlatformVisible = true">添加平台</el-button>
        </div>
      </div>
      <!--平台列表-->
      <el-table v-loading="loading" :data="dkTableData" class="w-full min-h-[calc(100vh-350px)]" stripe height="calc(100vh - 250px)">
        <el-table-column label="平台ID" prop="plaid" width="80" />
        <el-table-column label="排序" prop="sort" width="80" />

        <el-table-column prop="icon" label="平台信息">
          <template #default="{ row }">
            <div class="flex items-center">
              <div class="w-80px h-80px mr">
                <el-image :src="row.logo" alt="" class="w-80px h-80px rounded-10px">
                  <template #error>
                    <img src="@/assets/default/addon.png" alt="" style="width: 80px" />
                  </template>
                </el-image>
              </div>
              <div class="flex-1">
                <p>
                  <span class="text-14px font-bold">{{ row.name }}</span>
                </p>
                <p>
                  <dk-platform-type-tag :type="row.type" :type-name="row.type_name" :app-type="row.app_type" />
                </p>
                <p class="text-12px text-ellipsis overflow-hidden color-gray max-w-400px min-w-200px line-clamp-2">
                  {{ row.description }}
                </p>
              </div>
            </div>
          </template>
        </el-table-column>
        <!--
        <el-table-column v-if="!tabsName" prop="status" label="状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="停用"
              @change="() => onChangePlatformStatus(scope.row.plaid)"
            />
          </template>
        </el-table-column> -->
        <el-table-column prop="uid" label="所属用户" width="200" align="center">
          <template #default="{ row }">
            <div class="cursor-pointer" @click="getUserForm(row.plaid)">
              <p>
                <el-avatar :size="40" :src="row.user.avatar" />
              </p>
              <p>{{ row.user.username }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="tabsName === '0'" label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" @click="handlePlatformManage(scope.row.plaid, scope.row.type_mark)">操作台</el-button>
          </template>
        </el-table-column>
        <el-table-column v-else label="操作" width="180">
          <template #default="scope">
            <el-button type="success" @click="handleRecoverPlatform(scope.row.plaid)">恢复</el-button>
            <el-button type="danger" @click="handleDestroyPlatform(scope.row.plaid)">清除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mt-20px"
        background
        :page-sizes="[7, 10, 20, 50]"
        :layout="'sizes,total, ->, prev, pager, next, jumper'"
        :total="total"
        :current-page="page"
        :page-size="pageSize"
        @current-change="currentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <el-dialog v-model="dialogChoosePlatformVisible" title="添加平台">
      <div>
        <ul class="grid grid-cols-2 gap-2.5">
          <li
            v-for="(item, key) in platformTypes"
            :key="key"
            class="border border-gray-300 p-5 text-center cursor-pointer hover:bg-gray-100 hover:text-blue-500"
            @click="handleAddPlatform(item.type)"
          >
            <i :class="'iconfont ' + item.icon" class="text-3xl" />
            <p class="py-2.5">{{ item.addText }}</p>
          </li>
        </ul>
      </div>
    </el-dialog>
    <dk-form ref="editForm" :form-data="formData" :is-dialog="true" top="20vh" @submit="onSubmitUser" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { changePlatformStatus, getPlatformList, editUserForm, destroyPlatform, recoveryPlatform } from '@/api/platform'

defineOptions({
  name: 'PlatformList'
})

const router = useRouter()
const route = useRoute()

const page = ref(1)
const pageSize = ref(7)
const total = ref(0)
const dkTableData = ref([])
const searchData = reactive({
  name: '',
  type: parseInt(route.query.type) || ''
})
const order = 'sort desc ,plaid desc'
const dialogChoosePlatformVisible = ref(false)
const formData = ref(null)
const tabsName = ref('0')
const platformTypes = [
  { value: 1, label: '微信公众号', addText: '微信公众号', icon: 'icon-wechat', type: 'wechat' },
  { value: 2, label: '小程序集', addText: '小程序集', icon: 'icon-wxapp', type: 'app' },
  { value: 3, label: '企业微信', addText: '企业微信', icon: 'icon-work-wechat', type: 'work_wechat' },
  { value: 4, label: '抖音', addText: '抖音', icon: 'icon-douyin', type: 'douyin' },
  { value: 5, label: '自由平台', addText: '自由平台', icon: 'icon-free', type: 'free' }
]
const loading = ref(true)
const editForm = ref(null)

onMounted(() => {
  getList(page.value)
})

const handleTabClick = (e) => {
  tabsName.value = e.paneName
  getList(1)
}

const onReset = () => {
  searchData.name = ''
  searchData.type = ''
  getList(1)
}

const handleAddPlatform = (type) => {
  router.push({ path: '/platform/' + type + '/add' })
}

const handlePlatformManage = (id, type) => {
  type = type == 'min_app' ? 'app' : type
  router.push({ path: '/' + type, query: { p: id } })
}

const onSearch = () => {
  getList(1)
}

const currentChange = (p) => {
  getList(p)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  getList(1)
}

const onChangePlatformStatus = (id) => {
  changePlatformStatus(id).then((res) => {
    ElMessage.success(res.msg)
  })
}

const getList = (p) => {
  dkTableData.value = []
  page.value = p
  getPlatformList(page.value, pageSize.value, searchData, order, tabsName.value).then((res) => {
    dkTableData.value = res.data
    total.value = parseInt(res.msg)
    loading.value = false
  })
}

const getUserForm = (id) => {
  if (tabsName.value === '0') {
    editUserForm(id).then((res) => {
      formData.value = res.data
      editForm.value.show()
    })
  }
}

const onSubmitUser = () => {
  getList(page.value)
}

// 恢复平台
const handleRecoverPlatform = (plaid) => {
  ElMessageBox.confirm('此操作将恢复平台, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      recoveryPlatform(plaid).then((res) => {
        ElMessage.success(res.msg)
        getList(page.value)
      })
    })
    .catch(() => {})
}

// 清除平台
const handleDestroyPlatform = (plaid) => {
  ElMessageBox.prompt('此操作将永久删除该平台数据并通知所有应用,是否继续?', '提示', {
    inputPlaceholder: '请输入：确认删除',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(({ value }) => {
      if (value === '确认删除') {
        destroyPlatform(plaid).then((res) => {
          ElMessage.success(res.msg)
          getList(page.value)
        })
      } else {
        ElMessage.info('输入的内容不对')
      }
    })
    .catch(() => {})
}
</script>
